<template>
  <div class="ImageDetection">
    <div class="select">
      <label for="class" class="classLabel">选择班级：</label>
      <select id="class" v-model="selectedClass">
        <option disabled selected>选择班级</option>
        <option v-for="Class in Classes" :key="Class" :value="Class">
          {{ Class }}
        </option>
      </select>
      <label for="course" class="courseLabel">选择课程：</label>
      <select id="course" v-model="selectedCourse">
        <option disabled selected>选择课程</option>
        <option v-for="Course in Courses" :key="Course" :value="Course">
          {{ Course }}
        </option>
      </select>
      <button class="start" @click="Detection">开始检测</button>
      <label class="tip1">{{ tip1 }}</label>
    </div>
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="handleImageChange"
    />
    <div>
      <div class="picture" @click="triggerFileInput">
        <h6 class="tip" v-show="!SelectedVideo">选择视频</h6>
        <video
          v-if="SelectedVideo"
          controls
          :src="SelectedVideo"
          style="width: 100%; height: 100%"
        ></video>
      </div>
      <div class="pictureOfHistogram">
        <Histogram :number="numberOfActions"></Histogram>
      </div>
      <div class="pictureOfData">
        <h6 class="tip2">点击检测查看分析图</h6>
        <img
          v-if="image"
          :src="image"
          style="width: 400px; height: 230px"
        />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { serverAddress } from "../js/config";
import Histogram from "./Histogram.vue";
export default {
  name: "ImageDetection",
  components: {
    serverAddress,
    Histogram,
  },
  data() {
    return {
      videoElement: null,
      selectedClass: null,
      selectedCourse: null,
      Classes: [1, 2, 3, 4, 5],
      Courses: [
        "高等数学",
        "Java程序设计",
        "大学英语",
        "概率论",
        "计算机组成原理",
        "数据库原理",
      ],
      SelectedVideo: null,
      ToVideo: null,
      tip1: "",
      numberOfActions: [0, 0, 0, 0, 0],
      reachNumber: 0,
      absentNumber: 0,
      attendanceRate: 0,
      nowTime:'',
      image:null,
    };
  },
  mounted() {
    // 获取video元素的引用
    this.videoElement = this.$refs.SelectedVideo;

    // 添加播放事件监听器
    this.videoElement.addEventListener('timeupdate', this.handleTimeUpdate);
  },
  beforeDestroy() {
    // 在组件销毁前移除事件监听器，以防止内存泄漏
    this.videoElement.removeEventListener('timeupdate', this.handleTimeUpdate);
  },
  methods: {
    handleTimeUpdate() {
      // 获取当前播放时间
      const currentTime = this.videoElement.currentTime;

      // 检查是否每隔15秒
      if (currentTime % 15 === 0) {
        const currentSeconds = Math.floor(currentTime);//当前秒数
        this.sendRequest(currentSeconds);
      }
    },
    triggerFileInput() {

      this.$refs.fileInput.click();
    },
    handleImageChange(event) {
        const file = event.target.files[0];
        this.ToVideo = file;
        if (file) {
        const blobUrl = URL.createObjectURL(file);
        this.SelectedVideo = blobUrl;
        }
    },
    Detection() {
      console.log(this.selectedClass);
      if (
        this.selectedClass !== null &&
        this.selectedCourse !== null &&
        this.ToVideo != null
      ) {
        let form
        const loading = this.$loading({
          target:document.querySelector('.picture'),
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(100, 100, 100, 0.3)'
        });
        Data = new FormData();
        /* var url='https://mock.apifox.com/m2/3662090-0-default/137886205'; */
        var url= `${serverAddress}/VideoUpload/root`;

        // 向 FormData 对象添加数据
        formData.append("class_idd", this.selectedClass);
        formData.append("course_name", this.selectedCourse);
        if(sessionStorage.getItem('Identity')==='教师'){
          url= `${serverAddress}/VideoUpload/teacher`;
          /* url='https://mock.apifox.com/m2/3662090-0-default/137886162'; */
          formData.append(
          "teacher_id",
          sessionStorage.getItem('Id'),);
        }
        this.nowTime=this.getNowTime();
        formData.append("time",this.nowTime);
        formData.append("videoUpload", this.ToVideo);

        console.log(formData);
        axios({
          url:url,
          method: "POST",
          data: formData, // 使用 FormData 对象作为请求的数据
          headers: {
            "Content-Type": "multipart/form-data", // 设置请求头 Content-Type
          },
        }).then((response) => {
          loading.close();
          if (response.data.code === 1) {
            console.log(response.data);
            this.SelectedVideo=response.data.data;
            console.log(response.data.data);
          } else {
            console.log(response.data);
          }
        });
      } else {
        this.tip1 = "请确认班级，课程，图片均不为空";
        setTimeout(() => {
          this.tip1 = "";
        }, 5000);
      }
    },
    sendRequest(time){
      if(!this.stopCondition){//如果stopCondition为false则可以发送
      let formData = new FormData();
        /* var url='https://mock.apifox.com/m2/3662090-0-default/138244128'; */
        var url= `${serverAddress}/VideoUpload/information/root`;

        formData.append("class_idd", this.selectedClass);
        formData.append("course_name", this.selectedCourse);
        if(sessionStorage.getItem('Identity')==='教师'){
          /* url='https://mock.apifox.com/m2/3662090-0-default/138244095'; */
          url= `${serverAddress}/VideoUpload/information/teacher`;
          formData.append(
          "teacher_id",
          sessionStorage.getItem('Id'),);
        }
        formData.append("nowTime",this.nowTime);
        formData.append("time",time);
        console.log(formData);
        axios({
          url:url,
          method: "POST",
          data: formData, 
          headers: {
            "Content-Type": "multipart/form-data", 
          },
        }).then((response) => {
          if (response.data.code === 1) {
            console.log(response.data);
            this.$set(this, "numberOfActions", [
              response.data.data.pictureReadCount,
              response.data.data.pictureHandsCount,
              response.data.data.pictureWriteCount,
              response.data.data.absentNumber,
              response.data.data.pictureNumber -
                response.data.data.pictureReadCount -
                response.data.data.pictureHandsCount -
                response.data.data.pictureWriteCount,
            ]);
            console.log(this.numberOfActions);
            this.reachNumber = response.data.data.pictureNumber;
            this.absentNumber = response.data.data.absentNumber;
            this.attendanceRate = response.data.data.pictureRatio;
            this.image=response.data.data.changeFileAddr; 
          } else {
            console.log(response.data);
          }
        });
      }
    },
    getNowTime(){
         return new Date().toLocaleString();
    }
  },
};
</script>

<style scoped>
.tip1 {
  color: rgb(217, 83, 83);
  font-size: 15px;
  width: 380px;
  height: 20px;
  position: absolute;
  top: 13%;
  left: 68%;
  z-index: 50;
}
.pictureOfHistogram {
  width: 430px;
  height: 270px;
  position: absolute;
  top: 110px;
  left: 710px;
}
.start {
  text-align: center;
  padding: 9px;
  border: 2px solid #a1bce1;
  border-radius: 23px;
  font-weight: 700;
  font-size: 17px;
  width: 120px;
  background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
  color: #fff;
  position: absolute;
  top: 6%;
  right: 18%;
}
.tip {
  color: #a1bce1;
  font-size: 20px;
  font-weight: 300;
  font-family: "黑体";
  position: absolute;
  top: 35%;
  left: 44%;
}
.tip2 {
  color: #a1bce1;
  font-size: 15px;
  font-weight: 300;
  font-family: "黑体";
  position: absolute;
  top: 33%;
  left: 35%;
}
.picture {
  border: 1.5px dashed #a1bce1;
  width: 660px;
  height: 470px;
  position: absolute;
  top: 22%;
  left: 3%;
}
.pictureOfData {
  border: 1px solid #a1bce1;
  width: 410px;
  height: 240px;
  position: absolute;
  top: 57.8%;
  left: 61%;
}
#class,
#course {
  width: 100px;
  height: 30px;
  border: 2px solid #a1bce1;
  border-radius: 10px;
  position: absolute;
  top: 9%;
}
.classLabel,
.courseLabel {
  font-size: 17px;
  font-family: "黑体";
  position: absolute;
  top: 10%;
}
.classLabel {
  left: 11.5%;
}
.courseLabel {
  left: 31.5%;
}
#class {
  left: 18%;
}
#course {
  left: 38%;
}
</style>